<?php

namespace App\Console\Commands;

use App\Http\Services\ApiServices;
use App\Lib\Search;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class EsupdateChatFriend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $table = 'finance_wallet';

    protected $union_user_table = 'union_user';//公会成员表
    protected $union_table = 'union';//公会表
    protected $user_table = 'user';//用户表
    protected $logion_log = 'user_login_log';//登录表
    protected $chat_friend_baseinfo_table = 'chat_friend_baseinfo';//用户审核资料表
    protected $apiService;
    protected $userOnlineMap = 'USER:ONLINE';
    protected $EsLock = 'ES:UPDEATE:CHATFRIEND';

    protected $signature = 'EsupdeatedChatFriend';

    protected $log = 'esupdeate_chatfriend';
    protected $error_log = 'error_esupdeated_chatfriend';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户实时统计-交友聊天列表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->apiService = new ApiServices();
    }
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        set_time_limit(0);
    
        do {
            redis_lock($this->EsLock,60);
            //更新用户数据
            $this->userUpdeate();
            //更新主播数据
            $this->anchorUpdeate();
            redis_unlock($this->EsLock);
        } while (false);

    }
    
    //主播更新数据
    public function anchorUpdeate(){
        //查询已认证公会主播数据
        $union_user = DB::table($this->union_user_table)
                        ->leftJoin($this->union_table,$this->union_table.'.id',$this->union_user_table.'.un_id')
                        ->where('authentication_status','>',0)
                        ->get([$this->union_user_table.'.user_id']);
        $union_user = $this->objToArray($union_user);
        if(!empty($union_user)){
            //查询主播用户资料是否齐全
            $userBaseInfo = DB::table($this->user_table)
                            ->leftJoin($this->chat_friend_baseinfo_table,$this->chat_friend_baseinfo_table.'.user_id',$this->user_table.'.user_id')
                            ->leftJoin($this->table,$this->table.'.user_id',$this->user_table.'.user_id')
                            ->where($this->chat_friend_baseinfo_table.'.status',1)
                            ->whereIn('user.user_id',$union_user)
                            ->orderBy('charm_balance','desc')
                            ->get();
            $userBaseInfo = $this->objToArray($userBaseInfo); 
            $userIds = array_column($userBaseInfo,'user_id');

            //查看用户是否在线
            $isOnlineArr = Redis::HKEYS($this->userOnlineMap);

            if(!empty($userBaseInfo)){
                //更新es
                $search = new Search();
                $checkIdex = $search->checkIndexExists('chat_friend_anchor_user');

                if(!$checkIdex){
                    $params = ['index'=>'chat_friend_anchor_user'];
                    $search->createIndex($params);
                }
                //查询是否有期间更改主播资料的,因为改过的就变成未审核状态,不计入列表
                $query = [
                    'match_all' => new \stdClass()
                ];
                $esres = $search->getSearchData('chat_friend_anchor_user','user',30,0,$query);
                if(!empty($esres['total'])){
                    //取出所有user_id
                    $allpage = ceil($esres['total']/100);
                    $esuserIds = [];
                    for($i=0;$i<=$allpage;$i++){
                        $esRes = $search->getSearchData('chat_friend_anchor_user','user',100,$i,$query);
                        $esuserIds = array_merge(array_column($esRes['data'],'user_id'),$esuserIds);
                    }
                    //对比目前要如库的userID
                    $diffArr = array_diff($esuserIds,$userIds);
                    if(!empty($diffArr)){
                        //删除索引
                        foreach($diffArr as $del){
                            $search->delValue('chat_friend_anchor_user','user',$del);
                        }
                    }
                }
                //更新目前符合审核通过,资料齐全的主播
                foreach($userBaseInfo  as $key=>$v){
                    if(!empty($isOnlineArr) && in_array($v['user_id'],$isOnlineArr)){
                        $v['charm_balance'] = (int)$v['charm_balance'];
                        $v['is_online'] = 1;
                        //查询数据是否存在
                        $query = [
                            'multi_match' => [
                                'query' => $v['user_id'],
                                'fields' => ['user_id']
                            ]
                        ];
                        $esSearchres = $search->getSearchData('chat_friend_anchor_user','user',30,0,$query);
                        if(!empty($esSearchres['data'])){
                            $search->updateUser($v,'chat_friend_anchor_user');
                        }else{
                            $search->indexUser($v,'chat_friend_anchor_user');
                        }
                    }else{
                        $search->delValue('chat_friend_anchor_user','user',$v['user_id']);
                    }
                    
                }
            }else{
                write_log($this->log,'ERROR 数据不存在',$userBaseInfo);
            }
        }else{
            write_log($this->log,'ERROR 非认证公会',$union_user);
        }
        
    }

    //更新用户数据
    public function userUpdeate(){
        //过滤用户数组
        //$today = Carbon::now()->startOfDay()->toDateTimeString();
	//$enday = Carbon::now()->addDays(2)->endOfDay()->toDateTimeString();

        $enday = Carbon::now()->startOfDay()->toDateTimeString();
        $today = Carbon::now()->subDays(5)->endOfDay()->toDateTimeString();

        $res = DB::table($this->user_table)
                ->whereBetween('create_time',[$today,$enday])
                ->get(['user_id','create_timestamp']);
        $res = $this->objToArray($res);

        $finalArr = [];
        if(!empty($res)){
           $finalArr = array_column($res,'user_id');
        }

        //获取财富值小于1级的用户
        $userIds = DB::table($this->table)->where("wealth_balance",'<',1000)->whereIn('user_id',$finalArr)->get(['user_id']);

        $userIds = $this->objToArray($userIds);

        $finalArr = [];
        $finalArr = array_column($userIds,'user_id');

        if(!empty($finalArr)){
            //非主播身份用户
            $unUserInfo = DB::table($this->union_user_table)
                        ->leftJoin($this->union_table,$this->union_user_table.'.un_id',$this->union_table.'.id')
                        ->where('authentication_status','>',0)
                        ->whereIn('user_id',$finalArr)
                        ->get(['user_id','un_id','authentication_status']);
            $unUserInfo = $this->objToArray($unUserInfo);
	    $unUserArr = array_column($unUserInfo,'user_id');
//	    write_log($this->log,'$unUserArr',$unUserArr);
            $finalArr = [];
            foreach($userIds as $arr){
                if(!in_array($arr['user_id'],$unUserArr)){
                    array_push($finalArr,$arr['user_id']);
                }
            }
        }
        $userInfos = DB::table($this->user_table)->whereIn('user_id',$finalArr)->get();
        $userInfos = $this->objToArray($userInfos);
        $search = new Search();
        $checkIdex = $search->checkIndexExists('chat_friend_user');
        if(!$checkIdex){
            $params = ['index'=>'chat_friend_user'];
            $search->createIndex($params);
        }
        //先去除去原有es内数据用户可能不满足条件了
        $query = [
            'match_all' => new \stdClass()
        ];
        $esres = $search->getSearchData('chat_friend_user','user',30,0,$query);
        if(!empty($esres['total'])){
            //取出所有user_id
            $allpage = ceil($esres['total']/100);
            $esuserIds = [];
            for($i=0;$i<=$allpage;$i++){
                $esRes = $search->getSearchData('chat_friend_user','user',100,$i,$query);
                $esuserIds = array_merge(array_column($esRes['data'],'user_id'),$esuserIds);
            }
            //对比目前要如库的userID
            $diffArr = array_diff($esuserIds,$finalArr);
            if(!empty($diffArr)){
                //删除索引
                foreach($diffArr as $del){
                    $search->delValue('chat_friend_user','user',$del);
                }
            }
	}
//	write_log($this->log,'$finalArr',$finalArr);
        if(!empty($finalArr)){
            //链接ES
            foreach($userInfos  as $key=>$v){
                $search->indexUser($v,'chat_friend_user');
            }
        }
        
    }
    //返回数组
    public function objToArray($document)
    {
        return json_decode(json_encode($document), true);
    }


}
